<?php

namespace app\admin\controller\goods;

use app\admin\model\Attr;
use app\admin\model\AttrGroup;
use app\admin\model\GoodsPic;
use app\common\controller\Backend;
use think\Db;

/**
 * 商品
 *
 * @icon fa fa-circle-o
 */
class School extends Backend
{
    
    /**
     * School模型对象
     * @var \app\admin\model\goods\School
     */
    protected $model = null;
    protected $noNeedRight = '*';

    protected $searchFields = 'id,name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\School;
        $this->view->assign("kindList", $this->model->getKindList());
        $this->view->assign("isSchoolList", $this->model->getIsSchoolList());
        $this->view->assign("useAttrList", $this->model->getUseAttrList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->where(['is_school' => 2, 'is_delete' => 0, 'school_admin_id' => $this->auth->id])
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','price','cover_pic']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $row = $params['row'];

                if (!$row['use_attr'] && $row['price'] < 0) {
                    $this->error('课程价格不能小于0');
                }

                if (!$row['use_attr'] && !preg_match("/^[1-9][0-9]*$/" ,$row['goods_num'])) {
                    $this->error('请设置课程名额(正整数)');
                }

                $attr = [
                    [
                        'attr_list' => [
                            [
                                'attr_group_name' => '规格',
                                'attr_id' => 1,
                                'attr_name' => '默认',
                            ],
                        ],
                        'num' => $row['goods_num'],
                        'price' => 0,
                    ],
                ];
                if (isset($params['attr'])) {
                    $attr = $params['attr'];
                }

                if ($row['use_attr']) {
                    if (!$attr || !is_array($attr) || !count($attr)) {
                        $this->error('请填写课程属性');
                    }
                    foreach ($attr as $item) {
                        if ($item['price'] < 0) {
                            $this->error('课程属性价格不能小于0');
                        }
                    }
                }

                $this->model->store_id = 1;
                $this->model->name = $row['name'];
                $this->model->price = $row['price'];
                $this->model->cover_pic = $row['cover_pic'];
                $this->model->use_attr = $row['use_attr'];
                $this->model->detail = $row['detail'];
                $this->model->status = 1;
                $this->model->addtime = time();
                $this->model->integral = '{"more":""}';
                $this->model->is_level = 0;
                $this->model->is_school = 2;
                $this->model->school_admin_id = $this->auth->id;
                $this->model->attr = $attr;

                // 设置规格
                $new_attr = [];
                foreach ($attr as $i => $item) {

                    $new_attr_item = [
                        'attr_list' => [],
                        'num' => intval($item['num']),
                        'price' => doubleval($item['price']) ? doubleval($item['price']) : 0,
                        'supplier_price' => 0,
                        'no' => '',
                        'pic' => '',
                    ];

                    foreach ($item['attr_list'] as $a) {
                        $attr_group_model = AttrGroup::get(['store_id' => 1, 'attr_group_name' => $a['attr_group_name'], 'is_delete' => 0]);
                        if (!$attr_group_model) {
                            $attr_group_model = new AttrGroup();
                            $attr_group_model->attr_group_name = $a['attr_group_name'];
                            $attr_group_model->store_id = 1;
                            $attr_group_model->is_delete = 0;
                            $attr_group_model->save();
                        }
                        $attr_model = Attr::get(['attr_group_id' => $attr_group_model->id, 'attr_name' => $a['attr_name'], 'is_delete' => 0]);
                        if (!$attr_model) {
                            $attr_model = new Attr();
                            $attr_model->attr_name = $a['attr_name'];
                            $attr_model->attr_group_id = $attr_group_model->id;
                            $attr_model->is_delete = 0;
                            $attr_model->save();
                        }
                        $new_attr_item['attr_list'][] = [
                            'attr_id' => $attr_model->id,
                            'attr_name' => $attr_model->attr_name,
                        ];
                    }
                    $new_attr[] = $new_attr_item;
                }
                $this->model->attr = json_encode($new_attr, JSON_UNESCAPED_UNICODE);

                if ($this->model->save()) {
                    GoodsPic::destroy(['goods_id' => $this->model->id]);
                    if ($row['goods_pic']) {
                        $goods_pic_list = explode(',', $row['goods_pic']);
                        foreach ($goods_pic_list as $pic_url) {
                            $goods_pic = new GoodsPic();
                            $goods_pic->goods_id = $this->model->id;
                            $goods_pic->pic_url = $pic_url;
                            $goods_pic->is_delete = 0;
                            $goods_pic->save();
                        }
                    }

                    $this->success('添加成功');
                } else {
                    $this->error('添加失败, 请重试!');
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /*
     * 编辑
     * */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $goods_pic_List = Db::name('goods_pic')->where(['goods_id' => $ids])->column('pic_url');
        $goods_pic = implode(',', $goods_pic_List);

        // 规格组
        $attr_group_list = [];
        $num = 0;
        if ($row->use_attr) {
            $attr_data = json_decode($row->attr, true);
            foreach ($attr_data as $i => $attr_data_item) {
                foreach ($attr_data[$i]['attr_list'] as $j => $attr_list) {
                    $attr_group = Db::name('attr_group')
                        ->where('id','in',DB::name('attr')->where('id', $attr_data[$i]['attr_list'][$j]['attr_id'])->distinct(true)->column('attr_group_id'))
                        ->find();
                    if ($attr_group) {
                        $in_list = false;
                        foreach ($attr_group_list as $k => $exist_attr_group) {
                            if ($exist_attr_group['attr_group_name'] == $attr_group['attr_group_name']) {
                                $attr_item = [
                                    'attr_id' => $attr_data[$i]['attr_list'][$j]['attr_id'],
                                    'attr_name' => $attr_data[$i]['attr_list'][$j]['attr_name'],
                                ];
                                if (!in_array($attr_item, $attr_group_list[$k]['attr_list'])) {
                                    $attr_group_list[$k]['attr_list'][] = $attr_item;
                                }
                                $in_list = true;
                            }
                        }
                        if (!$in_list) {
                            $attr_group_list[] = [
                                'attr_group_name' => $attr_group['attr_group_name'],
                                'attr_list' => [
                                    [
                                        'attr_id' => $attr_data[$i]['attr_list'][$j]['attr_id'],
                                        'attr_name' => $attr_data[$i]['attr_list'][$j]['attr_name'],
                                    ],
                                ],
                            ];
                        }
                    }
                }
                $num += $attr_data_item['num'];
            }
        } else {
            $attr_data = json_decode($row->attr, true);
            foreach ($attr_data as $i => $attr_data_item) {
                $num += $attr_data_item['num'];
            }
        }

        $row->goods_num = $num;

        //规格
        $attr_row_list = [];
        if ($row->use_attr) {
            $attr_row_list = json_decode($row->attr, true);
            foreach ($attr_row_list as $i => $attr_row) {
                foreach ($attr_row['attr_list'] as $j => $attr) {
                    $group = Db::name('attr_group')->where('id', 'in', Db::name('attr')->where(['id' => $attr['attr_id']])->column('attr_group_id'))->find();
                    $attr_row_list[$i]['attr_list'][$j]['attr_group_name'] = $group ? $group['attr_group_name'] : '';
                }
            }
        }

        $attr_data = [
            'attr_group_list' => $attr_group_list,
            'attr_row_list' => $attr_row_list,
            'attr' => $row->attr,
            'model' => $row,
        ];

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $goods = $params['row'];

                if (!$goods['use_attr'] && $goods['price'] < 0) {
                    $this->error('价格不能小于0');
                }

                if (!$goods['use_attr'] && !preg_match("/^[1-9][0-9]*$/" ,$goods['goods_num'])) {
                    $this->error('请设置课程名额(正整数)');
                }

                $attr_one = [
                    [
                        'attr_list' => [
                            [
                                'attr_group_name' => '规格',
                                'attr_id' => 1,
                                'attr_name' => '默认',
                            ],
                        ],
                        'num' => isset($goods['goods_num']) ? $goods['goods_num'] : 0,
                        'price' => 0,
                    ],
                ];

                $attr = isset($params['attr']) ? $params['attr'] : $attr_one;

                if ($goods['use_attr']) {
                    if (!$attr || !is_array($attr) || !count($attr)) {
                        $this->error('请填写课程属性');
                    }
                    foreach ($attr as $item) {
                        if ($item['price'] < 0) {
                            $this->error('课程属性价格不能小于0');
                        }
                    }
                }

                $row->store_id = 1;
                $row->name = $goods['name'];
                $row->price = $goods['price'];
                $row->cover_pic = $goods['cover_pic'];
                $row->use_attr = $goods['use_attr'];
                $row->detail = $goods['detail'];

                // 设置规格
                $new_attr = [];
                foreach ($attr as $i => $item) {
                    $new_attr_item = [
                        'attr_list' => [],
                        'num' => intval($item['num']),
                        'price' => doubleval($item['price']),
                        'supplier_price' => 0,
                        'no' => '',
                        'pic' => '',
                    ];

                    foreach ($item['attr_list'] as $a) {
                        $attr_group_model = AttrGroup::get(['store_id' => 1, 'attr_group_name' => $a['attr_group_name'], 'is_delete' => 0]);
                        if (!$attr_group_model) {
                            $attr_group_model = new AttrGroup();
                            $attr_group_model->attr_group_name = $a['attr_group_name'];
                            $attr_group_model->store_id = 1;
                            $attr_group_model->is_delete = 0;
                            $attr_group_model->save();
                        }
                        $attr_model = Attr::get(['attr_group_id' => $attr_group_model->id, 'attr_name' => $a['attr_name'], 'is_delete' => 0]);
                        if (!$attr_model) {
                            $attr_model = new Attr();
                            $attr_model->attr_name = $a['attr_name'];
                            $attr_model->attr_group_id = $attr_group_model->id;
                            $attr_model->is_delete = 0;
                            $attr_model->save();
                        }
                        $new_attr_item['attr_list'][] = [
                            'attr_id' => $attr_model->id,
                            'attr_name' => $attr_model->attr_name,
                        ];
                    }
                    $new_attr[] = $new_attr_item;
                }
                $row->attr = json_encode($new_attr, JSON_UNESCAPED_UNICODE);

                if ($row->save() !== false) {
                    GoodsPic::destroy(['goods_id' => $ids]);
                    if ($goods['goods_pic']) {
                        $goods_pic_list = explode(',', $goods['goods_pic']);
                        foreach ($goods_pic_list as $pic_url) {
                            $goods_pic = new GoodsPic();
                            $goods_pic->goods_id = $ids;
                            $goods_pic->pic_url = $pic_url;
                            $goods_pic->is_delete = 0;
                            $goods_pic->save();
                        }
                    }

                    $this->success('修改成功');
                } else {
                    $this->error('修改失败, 请重试!');
                }

                /*$params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }*/
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("goods_pic", $goods_pic);
        $this->view->assign("attr_data", json_encode($attr_data));
        return $this->view->fetch();
    }

    /*
     * 查看课程详情
     * */
    public function detail($ids = '')
    {
        // 商品信息
        $goods = Db::name('goods')->alias('g')
            ->where(['g.id' => $ids, 'g.is_delete' => 0])
            ->field('g.id, g.name, g.price, g.detail, g.sort, g.cover_pic, g.goods_num, g.attr, g.use_attr')
            ->find();

        //轮播图
        $goods_pic_list = Db::name('goods_pic')->where(['goods_id' => $goods['id'], 'is_delete' => 0])->column('pic_url');

        //规格组
        $num = 0;
        $attr_group_list = [];
        $attr_data = json_decode($goods['attr'], true);
        foreach ($attr_data as $i => $attr_data_item) {
            foreach ($attr_data[$i]['attr_list'] as $j => $attr_list) {
                $attr_group = Db::name('attr_group')
                    ->where('id','in',DB::name('attr')->where('id', $attr_data[$i]['attr_list'][$j]['attr_id'])->distinct(true)->column('attr_group_id'))
                    ->find();
                if ($attr_group) {
                    $in_list = false;
                    foreach ($attr_group_list as $k => $exist_attr_group) {
                        if ($exist_attr_group['attr_group_name'] == $attr_group['attr_group_name']) {
                            $attr_item = [
                                'attr_id' => $attr_data[$i]['attr_list'][$j]['attr_id'],
                                'attr_name' => $attr_data[$i]['attr_list'][$j]['attr_name'],
                            ];
                            if (!in_array($attr_item, $attr_group_list[$k]['attr_list'])) {
                                $attr_group_list[$k]['attr_list'][] = $attr_item;
                            }
                            $in_list = true;
                        }
                    }
                    if (!$in_list) {
                        $attr_group_list[] = [
                            'attr_group_name' => $attr_group['attr_group_name'],
                            'attr_list' => [
                                [
                                    'attr_id' => $attr_data[$i]['attr_list'][$j]['attr_id'],
                                    'attr_name' => $attr_data[$i]['attr_list'][$j]['attr_name'],
                                ],
                            ],
                        ];
                    }
                }
            }
            $num += $attr_data_item['num'];
        }
        $goods['goods_num'] = $num;

        //规格
        $attr_row_list = [];
        if ($goods['use_attr']) {
            $attr_row_list = json_decode($goods['attr'], true);
            foreach ($attr_row_list as $i => $attr_row) {
                foreach ($attr_row['attr_list'] as $j => $attr) {
                    $group = Db::name('attr_group')->where('id', 'in', Db::name('attr')->where(['id' => $attr['attr_id']])->column('attr_group_id'))->find();
                    $attr_row_list[$i]['attr_list'][$j]['attr_group_name'] = $group ? $group['attr_group_name'] : '';
                }
            }
        }

        $this->assign('goods', $goods);
        $this->assign('goods_pic_list', $goods_pic_list);
        $this->assign('attr_group_list', $attr_group_list);
        $this->assign('attr_row_list', $attr_row_list);

        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        $row = $this->model->get($ids);
        if(!$row){
            $this->error(__("No results were found"));
        }
        $rst = array(
            'code' => 0,
            'msg' => '删除失败, 请重试!',
            'data' => '$row',
            'url' => '',
            'wait' => '3'
        );
        if($this->request->isPost()){
            $row->is_delete = 1;
            $row->save();
            $rst['code'] = 1;
            $rst['msg'] = '删除成功';
        }

        return json($rst);
    }

}
